﻿var SelectareDimensiuniPage = function(pageContainer) {

    SelectareDimensiuniPage.superclass.constructor.call(this, pageContainer);

    var self = this;
    this.CanGoBack = false;

    var struct_id = 0;
    var searchBar = null;
    var currentIndex = 0;
    var initialPageSize = 50;
    var pageSize = 20;
    var searchResultsInfo = null;

    var isLoading = false;
    var visibleElements = 0;
    var dimensiuni = new Array();
    var currentCallback = null;

    var Elements = {
        dimensiuniList: pageContainer.find(".dimensiuniList"),
        loader: pageContainer.find(".loadMore")
    };

    var Templates = {
        dimensiuneTemplate: pageContainer.find(".dimensiuniTemplate"),
        dimensiuneTemplateCompiled: null
    };

    self.initialize = override(self.initialize, function() {
        addSearchBar();
        addResultsInfo(Elements.dimensiuniList);
        app.translatePage(app.Pages.SelectareDimensiuniPage);

        pageContainer.bind('onBeforePageShow', function() {
            app.Phone.setBackbtnVisible(true);
        });

        pageContainer.bind('onPageHide', function() {
            currentCallback = null;
        });

        pageContainer.bind('onPageShow', function() {
            searchBar.reset();
        });
    });

    var addResultsInfo = function(element) {
        element.before($("#searchResultsInfoTemplate").html());
        var searchResultsInfoContainer = pageContainer.find(".search-results-container");
        searchResultsInfo = new SearchResultsInfo(searchResultsInfoContainer);
        searchResultsInfo.hide();
    };

    var addSearchBar = function() {
        pageContainer.find('.content').prepend($("#searchBarTemplate").html());
        var searchBarContainer = pageContainer.find(".content .search-bar:first");
        searchBar = new SearchBar(searchBarContainer);
        searchBar.initialize();

        searchBarContainer.show();
        searchBarContainer
            .bind('getData', function(e) {
                if (e.Data.reset)
                    resetList();
                self.getPullUpData();
            })
            .bind('cancel', function(e) {
                resetList();
                self.getPullUpData();
            });
    };

    this.refresh = function(cstr_id) {
        struct_id = cstr_id;
        resetList();
        self.getPullUpData();
    };

    var resetList = function() {
        currentIndex = 0;
        isLoading = false;
        Elements.dimensiuniList.empty();
        dimensiuni = new Array();
    };

    this.setCallback = function(callback) {
        currentCallback = callback;
    };

    this.getPullUpData = function(callback) {
        if (isLoading)
            return;

        isLoading = true;
        Elements.loader.show();
        var searchText = searchBar.getSearchText();
        var noItemsToLoad = currentIndex ? pageSize : initialPageSize;

        app.TMMService.Pontaj.GetDimensiuni(struct_id, searchText, 0, currentIndex, noItemsToLoad, function(response) {
            if (!response || response.Exception) {
                Elements.loader.hide();
                return app.MessagesFactory.showToastWarning(translate('General_EroareServer'));
            }

            if (response && response.FinalResult && currentIndex != response.FinalResult.StartIndex)
                return Elements.loader.hide();;

            addToList(response.FinalResult.Dimensiuni);

            if (!visibleElements)
                calculateVisibleElements();

            if (!response.FinalResult.Dimensiuni.length || (currentIndex == 0 && response.FinalResult.Dimensiuni.length < visibleElements))
                Elements.loader.hide();
            else if (!currentIndex)
                Elements.loader.show();

            currentIndex += response.FinalResult.Dimensiuni.length;
            isLoading = false;
        });
    };

    var calculateVisibleElements = function() {
        visibleElements = Math.ceil($(window).height() / Elements.dimensiuniList.find("li:first").outerHeight());
    };

    var addToList = function(data) {
        if (!data)
            return;

        if (!Templates.dimensiuneTemplateCompiled) {
            var source = Templates.dimensiuneTemplate.html();
            Templates.dimensiuneTemplateCompiled = Handlebars.compile(source);
        }

        var html = "";
        for (var i = 0; i < data.length; i++) {
            var c = data[i];
            dimensiuni.push(c);
            html += Templates.dimensiuneTemplateCompiled(c);
        }

        Elements.dimensiuniList.append(html);
        setActionsOnDimensiune();
    };

    var setActionsOnDimensiune = function() {
        Elements.dimensiuniList.find('.dimensiune').unbind().tap(function(e) {
            if (!currentCallback)
                return;

            var index = Elements.dimensiuniList.children().index($(this));
            var dim = dimensiuni[index];
            currentCallback(dim);

            return Event.stopEvent(e);
        });
    };

    this.setModuleAction = override(self.setModuleAction, function() {
        if (app.Phone)
            app.Phone.setModuleAction(ModuleActions.None);
    });

    self.initialize();
};
extend(SelectareDimensiuniPage, TMMobilePage);